package com.xsherl.leetcode.solution;

import com.xsherl.leetcode.utils.PrintUtils;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

public class ThreeSum {

    /**
     * 双指针
     * 对数组先进行排序
     * 最外层循环，然后变成求两数之和为固定值，
     *
     * @param nums
     *  0 <= nums.length <= 3000
     * -105 <= nums[i] <= 105
     * @return
     */
    public List<List<Integer>> threeSum(int[] nums) {
        int len = nums.length;
        List<List<Integer>> res = new ArrayList<>();
        Arrays.sort(nums);
        int pre = len - 1;
        for (int i = 0; i < len - 2; ++i){
            int x = nums[i];
            if (i > 0 && nums[i - 1] == x){
                continue;
            }
            int k = pre;
            for (int j = i + 1; j < len; ++j){
                int y = nums[j];
                int target = 0 - x - y;
                if (j > i + 1 && nums[j - 1] == y){
                    continue;
                }
                while (k > j && nums[k] > target){
                    k--;
                }
                if (k == j){
                    break;
                }
                if (j == i + 1){
                    pre = k;
                }
                if (k > j && nums[k] == target){
                    res.add(Arrays.asList(x, y, nums[k]));
                }
            }
        }
        return res;
    }

    public static void main(String[] args) {
        int[] nums = new int[]{-1,0,1,2,-1,-4};
        List<List<Integer>> lists = new ThreeSum().threeSum(nums);
        PrintUtils.println(lists);
    }

}
